package com.sundae.smarthomedemo.Utils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.sundae.smarthomedemo.Beans.DaoMaster;
import com.sundae.smarthomedemo.Beans.DaoSession;
import com.sundae.smarthomedemo.Beans.DeviceSQLBean;
import com.sundae.smarthomedemo.Beans.DeviceSQLBeanDao;

import java.util.ArrayList;

/**
 * Created by daijiyuan on 2017/6/7.
 * 邮箱 948820549@qq.com
 *
 * @Sundae
 */

public class DaoControl {
    private static DaoControl instance;
    private Context context;
    private DaoMaster daoMaster;
    private DaoMaster.DevOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoSession daoSession;
    private DeviceSQLBeanDao deviceSQLBeanDao;

    public static DaoControl getInstance(Context context)
    {
        if(instance == null)
        {
            synchronized (DaoControl.class)
            {
                instance = new DaoControl(context);
            }
        }
        return instance;
    }

    public DaoControl(Context context) {
        this.context = context;
        openDatabase();
    }

    public void openDatabase()
    {
        mHelper = new DaoMaster.DevOpenHelper(context.getApplicationContext() , "device_db" , null);
        db = mHelper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
        deviceSQLBeanDao = daoSession.getDeviceSQLBeanDao();
    }

    public void insert(DeviceSQLBean deviceSQLBean)
    {
        deviceSQLBeanDao.insert(deviceSQLBean);
    }

    public ArrayList<DeviceSQLBean> selectByUser(String username)
    {
        ArrayList<DeviceSQLBean> list = new ArrayList<>();
        for(DeviceSQLBean deviceSQLBean : deviceSQLBeanDao.loadAll())
        {
            if(deviceSQLBean.getUsername().equals(username))
            {
                list.add(deviceSQLBean);
            }
        }
        return list;
    }

    public DeviceSQLBean selectById(long id)
    {
        return deviceSQLBeanDao.load(id);
    }

    public void delete(long id)
    {
        deviceSQLBeanDao.deleteByKey(id);
    }

    public void update(DeviceSQLBean deviceSQLBean)
    {
        deviceSQLBeanDao.update(deviceSQLBean);
    }
}
